import {
  CallHandler,
  ExecutionContext,
  Inject,
  Injectable,
  NestInterceptor,
} from '@nestjs/common';
import AuthApi from '../api/auth.api';

@Injectable()
export default class AuthInterceptor implements NestInterceptor {
  @Inject(AuthApi)
  private authApi: AuthApi;
  async intercept(context: ExecutionContext, next: CallHandler): Promise<any> {
    const request = context.switchToHttp().getRequest() as Request;
    const token = request.headers['token'] as string;
    // 假设我们有一个服务用于验证 token
    const urlParts = request.url.split('/');
    await this.authApi.validateIdentity({
      token,
      service: urlParts[1],
      api: '/' + urlParts.slice(2).join('/'),
    });
    return next.handle();
  }
}
